﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.ComponentModel;
using System.Windows.Markup;

namespace Vision.Core.ActivityComponents.Assembly
{
    [ContentProperty("Body")]
    [Designer(typeof(CreateInstanceDesigner))]
    public class CreateInstance : NativeActivity
    {
        object instance = null;

        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        [DefaultValue(null)]
        [RequiredArgument]
        public InArgument<string> TypeName { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Browsable(false)]
        [DefaultValue(null)]
        public ActivityAction<object> Body { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public CreateInstance()
        {
            this.Body = new ActivityAction<object>()
            {
                Argument = new DelegateInArgument<object>()
                {
                    Name = "instanceObject"
                }
            };
        }

        protected override void Execute(NativeActivityContext context)
        {
            System.Reflection.Assembly assemblyObject = (System.Reflection.Assembly)context.Properties.Find("5D07EA7B-BF1C-4F15-A3F0-AA2B64588D78");
            if (assemblyObject != null)
            {
                // gets the type information of the requested object
                Type objType = assemblyObject.GetType(this.TypeName.Get(context));

                if (objType == null)
                {
                    throw new NotImplementedException("Type not found in assembly.");
                }

                // creates an instance of the requested object
                instance = Activator.CreateInstance(objType);
                context.Properties.Add("1ec83ea-51f8-4891-87c2-16638f870c3a", instance);

                context.ScheduleAction(this.Body, instance, this.OnChildActivityCompleted);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="completedInstance"></param>
        private void OnChildActivityCompleted(NativeActivityContext context, ActivityInstance completedInstance)
        {
            context.Properties.Remove("1ec83ea-51f8-4891-87c2-16638f870c3a");
            this.instance = null;
        }
    }
}
